import { FastifyInstance } from "fastify";
import { Static, Type } from "@sinclair/typebox";
import { Op } from "sequelize";
import { Organization, Event } from "@db";
import { config } from "@config";

const vacancyQuery = Type.Object({
    query: Type.Optional(Type.String()),
    page: Type.Optional(Type.Number({ default: 0 })),
});

export const event = async (fastify: FastifyInstance) => {
    fastify.get<{ Querystring: Static<typeof vacancyQuery> }>(
        "/student/event",
        {
            preHandler: fastify.auth("student"),
            schema: {
                tags: ["student"],
                querystring: vacancyQuery,
            },
        },
        async (req, res) => {
            const { page, query } = req.query;

            //спидкод не круто некрасиво ну и ладно
            const where: any = {};

            if (query)
                where.title = {
                    [Op.iLike]: `%${query}%`,
                };

            const { count, rows } = await Event.findAndCountAll({
                where,
                offset: page * 50,
                limit: 50,
                attributes: ["id", "title", "date", "skills", "organizationId"],
            });

            return res.send({
                pages: Math.ceil(count / 50),
                events: await Promise.all(
                    rows.map(async (event) => {
                        return {
                            ...event.dataValues,
                            organization: await Organization.findOne({
                                where: {
                                    id: event.organizationId,
                                },
                                attributes: ["name", "photo"],
                            }).then(({ id, name, photo, isVerified }) => {
                                return {
                                    id,
                                    name,
                                    photo: photo
                                        ? "https://" +
                                          config.host +
                                          "/files/organizationAvatars/" +
                                          photo
                                        : null,
                                    isVerified,
                                };
                            }),
                            organizationId: undefined,
                        };
                    })
                ),
            });
        }
    );
};
